package o2o.service.area;

import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.area.CityMemory;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.area.CityInfo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author qilonghe【1061268464@qq.com】
 * @ClassName ProvinceService
 * @Description:
 * @date 2020/9/17 0017 上午 10:04
 * @Version 1.0
 */
@Service
public class CityService {

    public List<CityInfo> list(String params, String cityCode) {
        return CityMemory.getInstance().list(params, cityCode);
    }

    public void add(CityInfo city, Boolean isAddList) throws Exception {
        // 查询数据库中是否存在相同编号的记录
        QueryCondition query = QueryCondition.getInstance();
        query.addCondition(Expression.getInstance().addChild("delFlag", 0).addChild("cityCode", city.getCityCode()));
        String sql = DaoUtils.getSql(PojoTables.CHN_CITY, query);
        List<CityInfo> list = (List<CityInfo>) DataDaoSql.getInstance().list(CityInfo.class, sql);
        if (ValidateUtil.isAbsList(list)) {
            // 存在该编号的市信息
            if (isAddList) {
                return;
            } else {
                new Exception("该编号已存在");
            }
        }
        city.setDelFlag(0);
        DataDaoSql.getInstance().insertObj(PojoTables.CHN_CITY, city);

        // 添加缓存
        CityMemory.getInstance().addCache(city.getCity());
    }

    public void modify(CityInfo city) throws Exception {
        DataDaoSql.getInstance().updateObj(PojoTables.CHN_CITY, city, "id", city.getId());

        // 更新缓存
        CityMemory.getInstance().modifyCache(city);
    }

    public void delete(Long id) throws Exception {
        CityInfo city = new CityInfo();
        city.setDelFlag(1);
        DataDaoSql.getInstance().updateObj(PojoTables.CHN_CITY, city, "id", id);

        // 删除缓存
        CityMemory.getInstance().deleteCache(id);
    }
}